package cn.hd.userService.service.user.impl;

import cn.hd.commonService.entity.SysRole;
import cn.hd.commonService.utils.ImageUtils;
import cn.hd.commonService.vo.Query;
import cn.hd.commonService.entity.SysUser;
import cn.hd.commonService.entity.SysUserRole;
import cn.hd.commonService.exception.CustomException;
import cn.hd.commonService.utils.NumberUtils;
import cn.hd.commonService.vo.user.UserRoleVo;
import cn.hd.userService.mapper.user.SysUserMapper;
import cn.hd.userService.service.role.ISysUserRoleService;
import cn.hd.userService.service.role.SysRoleService;
import cn.hd.userService.service.user.ISysUserService;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hd
 * @since 2022-06-26
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private  SysUserMapper userMapper;

    @Autowired
    private ISysUserRoleService sysUserRoleService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    @Qualifier("passwordEncoder")
    public PasswordEncoder passwordEncoder;

    /**
     * 用户注册
     * @param sysUser
     */
    public void register(SysUser sysUser){
        int maxOrderNo = maxOrderNo();
        sysUser.setPassword(passwordEncoder.encode("666666"));
        sysUser.setOrderNo(maxOrderNo);
        if (StrUtil.isBlankIfStr(sysUser.getNickName())){
            sysUser.setNickName("账户"+ NumberUtils.getRandomInt(4));
        }
        //检查合法性
        checkUser(sysUser);
        //保存用户
        userMapper.insert(sysUser);
    }

    /**
     * 用户修改
     * @CreatedBy dsl
     */
    @Override
    public void update(SysUser sysUser) {
        //根据id获取用户信息
        SysUser user = userMapper.selectById(sysUser.getRecordId());
        if (user == null){
            throw new CustomException("用户信息有误");
        }
        BeanUtils.copyProperties(sysUser,user,"password","enable","deleted","account","photo");
        checkUser(user);
        //根据用户id修改用户信息
        userMapper.updateById(user);
    }

    /**
     * 批量删除用户
     * @CreatedBy dsl
     */
    @Override
    public void deleteBatch(String uuids) {
        // 将前端传递的用户逐渐转化为list集合
        List<Integer> list = Convert.toList(Integer.class, uuids);
        for (Integer s : list) {
            List<SysUserRole> systemUserRoles = sysUserRoleService.getSysUserRoleByUserId(s,null);
            if (systemUserRoles!=null&&systemUserRoles.size()>0){
                throw new CustomException("当前用户关联的有系统角色，不能删除");
            }

        }
         userMapper.deleteBatchIds(list);
    }

    @Override
    public IPage<UserRoleVo> getListByPage(Query query, String condition) {
        IPage<UserRoleVo> userPage = userMapper.getListByPage(new Page<UserRoleVo>(query.getCurrentPage(),query.getPageSize()), condition);
        for (UserRoleVo user : userPage.getRecords()) {
            //根据userId获取关联的角色信息
            List<SysUserRole> userRoleByUserList = sysUserRoleService.getSysUserRoleByUserId(user.getRecordId());
            //获取角色id
            List<Integer> roleIds = userRoleByUserList.stream().map(sysUserRole -> sysUserRole.getRoleId()).collect(Collectors.toList());
            user.setRoleIds(StringUtils.strip(roleIds.toString(),"[]"));
            List<SysRole> roleList = sysRoleService.getRoleList(roleIds);
            List<String> roleNameList = roleList.stream().map(sysRole -> sysRole.getRoleName()).collect(Collectors.toList());
            user.setRoleNames(StringUtils.strip(roleNameList.toString(),"[]"));
        }
        return userPage;
    }

    /**
     * 查验用户是否合法
     * @param user
     */
    public void checkUser(SysUser user){
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getAccount,user.getAccount()).eq(SysUser::getDeleted,0).
                or()
                .eq(SysUser::getPhone,user.getPhone()).eq(SysUser::getDeleted,0)
                .or()
                .eq(SysUser::getEmail,user.getEmail()).eq(SysUser::getDeleted,0);
        SysUser one = userMapper.selectOne(wrapper);
        if (one!=null){
            if (StrUtil.isBlankIfStr(user.getRecordId())){//主健为空，表示是新增
               checkUserInfo(user,one);
            }else {
                if (!one.getRecordId().equals(user.getRecordId())){
                    checkUserInfo(user,one);
                }
            }
        }
    }
    public void checkUserInfo(SysUser user,SysUser one){
        if (user.getAccount().equals(one.getAccount())){
            throw new CustomException("账号重复");
        }
        if (user.getPhone().equals(one.getPhone())){
            throw new CustomException("电话重复");
        }
        if (user.getEmail().equals(one.getEmail())){
            throw new CustomException("邮箱重复");
        }
    }

    /**
     * 获取最大排序号
     * @return
     */
    public int maxOrderNo(){
        return Convert.toInt(userMapper.maxOrderNo(),0)+1;
    }


    @Override
    public SysUser getUserByAccount(String account) {
        //查询用户信息
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getAccount,account);
        SysUser user = getOne(queryWrapper);
        //如果没有查询到用户就抛出异常
        if(Objects.isNull(user)){
            throw new RuntimeException("用户名或者密码错误");
        }
        if (Convert.toInt(user.getEnable(),0) == 0){
            throw new CustomException("当前用户未启用，不能登录");
        }
        return user;
    }

    /**
     * 启用或禁用用户
     * @param userId
     * @param enable
     */
    @Override
    public void enableUser(Integer userId, Integer enable) {
        SysUser sysUser = userMapper.selectById(userId);
        if (sysUser == null){
            throw new CustomException("用户信息有误");
        }
        sysUser.setEnable(enable);
        userMapper.updateById(sysUser);
    }

    @Override
    public void updatePassword(Integer recordId, String account, String password) {
        SysUser sysUser = userMapper.selectById(recordId);
        if (sysUser == null){
            throw new CustomException("用户信息有误");
        }
        sysUser.setAccount(account);
        sysUser.setPassword(passwordEncoder.encode(password));
        //核实用户
        checkUser(sysUser);
        userMapper.updateById(sysUser);
    }

    @Override
    public SysUser getUserByUserId(Integer recordId) {
       SysUser sysUser =  userMapper.selectById(recordId);
       if (sysUser == null){
           throw new CustomException("用户信息有误");
       }
        return sysUser;
    }

    @Override
    public void uploadPhoto(Integer recordId, MultipartFile photo) throws Exception{
        SysUser sysUser =  userMapper.selectById(recordId);
        if (sysUser == null){
            throw new CustomException("用户信息有误");
        }
        InputStream stream = photo.getInputStream();
        //将流转化为base64字符串
        String photoStr = ImageUtils.streamToStr(stream);
        sysUser.setPhoto(photoStr);
        userMapper.updateById(sysUser);
    }
}
